package main;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.List;
import javax.microedition.lcdui.StringItem;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.*;
import util.CommonUtil;

/**
 * @author omega
 */
public class KamusMidlet extends MIDlet implements CommandListener {

    public static KamusMidlet midlet;
    public static Display display;
    Splash splash;
    MenuCanvas menuCanvas;
    //command
    Command cmdSearch;
    Command cmdExit;
    Command cmdAddWord;
    Command cmdChangeOri;
    Command cmdBack;
    Command cmdSelect;
    Command cmdSave;
    Command cmdMenu;
    Command cmdUpdate;
    Command cmdClear;
    Command cmdUpload;
    Command cmdDelete;
    Command cmdListWord;
    //end command
    //orientasi
    public byte orient = 0; // 0=gaul-ina, 1=ina-gaul
    byte[] arrOrient = {0, 1};
    String[] arrOrientName = {"GAUL - INA", "INA - GAUL"};
    String orientName = arrOrientName[orient];
    //end orientasi
    Form frmSearch;
    Form frmAddWord;
    Form frmUpdate;
    Form frmUpload;
    List listOri;
    List listNewWord;
    TextField txtWord;
    StringItem siResult;
    TextField txtGaul;
    TextField txtInd;
    TextField txtAuthor;
    Alert alert;
    //data
    KamusEngine engine;
    String[] arrNewWord = new String[0];
    //static
    static final String STR_UPLOAD = "Do you want upload your new data to server?";
    static final String STR_UPDATE = "Do you want update database with the newest version?";

    public KamusMidlet() {
        midlet = this;
        menuCanvas = new MenuCanvas();
        display = Display.getDisplay(this);
        cmdSearch = new Command("Search", Command.ITEM, 1);
        cmdExit = new Command("Exit", Command.EXIT, 2);
        cmdAddWord = new Command("Add New Word", Command.ITEM, 3);
        cmdChangeOri = new Command("Orientation", Command.ITEM, 4);
        cmdBack = new Command("Back", Command.EXIT, 5);
        cmdSelect = new Command("Select", Command.OK, 6);
        cmdSave = new Command("Save", Command.OK, 6);
        cmdMenu = new Command("Back", Command.CANCEL, 6);
        cmdUpdate = new Command("Update", Command.ITEM, 6);
        cmdClear = new Command("Clear", Command.ITEM, 6);
        cmdUpload = new Command("Upload", Command.ITEM, 6);
        cmdDelete = new Command("Delete All", Command.ITEM, 6);
        cmdListWord = new Command("List Word", Command.ITEM, 6);
        frmSearch = new Form("Kamus TST");
        frmAddWord = new Form("Add New Word");
        frmUpdate = new Form("Update Database");
        frmUpload = new Form("Upload New Word");
        txtWord = new TextField("Word", "", 1000, TextField.ANY);
        txtAuthor = new TextField("Author", "", 45, TextField.ANY);
        listOri = new List("Select Orientation", List.EXCLUSIVE, arrOrientName, null);
        listNewWord = new List("List New Word", List.EXCLUSIVE, arrNewWord, null);
        txtGaul = new TextField("Gaul", "", 1000, TextField.ANY);
        txtInd = new TextField("Indonesia", "", 1000, TextField.ANY);
        siResult = new StringItem("Search Result:", "");

        //set form addWord
        frmAddWord.append(txtGaul);
        frmAddWord.append(txtInd);
        frmAddWord.addCommand(cmdSave);
        frmAddWord.addCommand(cmdUpload);
        frmAddWord.addCommand(cmdListWord);
        frmAddWord.addCommand(cmdMenu);
        frmAddWord.setCommandListener(this);

        //set form main
        frmSearch.append(orientName);
        frmSearch.append(txtWord);
        frmSearch.append(siResult);
        frmSearch.addCommand(cmdSearch);
        frmSearch.addCommand(cmdClear);
        frmSearch.addCommand(cmdMenu);
        frmSearch.setCommandListener(this);

        //set list ori
        listOri.addCommand(cmdSelect);
        listOri.addCommand(cmdMenu);
        listOri.setCommandListener(this);

        //set form update
        frmUpdate.append(STR_UPDATE);
        frmUpdate.addCommand(cmdUpdate);
        frmUpdate.addCommand(cmdMenu);
        frmUpdate.setCommandListener(this);

        //set form upload
        frmUpload.append(STR_UPLOAD);
        frmUpload.append(txtAuthor);
        frmUpload.addCommand(cmdBack);
        frmUpload.addCommand(cmdUpload);
        frmUpload.setCommandListener(this);

        //set list new word
        listNewWord.addCommand(cmdBack);
        listNewWord.setCommandListener(this);

        //set alert
        alert = new Alert("", "", null, AlertType.CONFIRMATION);

        //data
        engine = new KamusEngine();

    }

    public void startApp() {
        splash = new Splash();
        display.setCurrent(splash);
        splash.startTimer();
        engine.loadData(KamusEngine.ORI_GAUL_IND);
    }

    public void pauseApp() {
    }

    public void destroyApp(boolean unconditional) {
    }

    public void exitMidlet() {
        destroyApp(false);
        notifyDestroyed();
    }

    /**
     * Tampilan setelah splash screen
     */
    public void splashTimeOut() {
        display.setCurrent(menuCanvas);
    }

    /**
     * menampilkan alert 
     * @param message
     */
    public void showAlert(String message) {
        alert.setString(message);
        display.setCurrent(alert, display.getCurrent());
    }

    public void commandAction(Command c, Displayable d) {
        if (d == frmSearch) {
            if (c == cmdSearch) {// proses pencarian
                if (txtWord.getString().trim().length() == 0) {
                    showAlert("Keyword must be filled");
                    return;
                }
                String result = engine.search(txtWord.getString().toLowerCase().trim());
                if (result == null) {
                    result = "Kata tidak ditemukan!";
                }
                siResult.setText(result);
            } else if (c == cmdClear) {
                txtWord.setString("");
                siResult.setText("");
            } else if (c == cmdMenu) {
                menuCanvas.reset();
                display.setCurrent(menuCanvas);
            }
        } else if (d == frmAddWord) {//proses penambahan kata -> simpan ke RMS 
            if (c == cmdMenu) {
                menuCanvas.reset();
                display.setCurrent(menuCanvas);
            } else if (c == cmdSave) { //simpan ke RMS
                txtGaul.setString(txtGaul.getString().toLowerCase().trim());
                txtInd.setString(txtInd.getString().toLowerCase().trim());
                if (txtGaul.getString().length() == 0 || txtInd.getString().length() == 0) {
                    showAlert("Input is not valid");
                    return;
                }
                if(!CommonUtil.validateInput(txtGaul.getString()) || !CommonUtil.validateInput(txtInd.getString())){
                    showAlert("Input is not valid");
                }
                if (engine.dbNewWord.getLength() == 20) {
                    showAlert("Input data maximum is 20");
                    return;
                }
                engine.dbNewWord.add(txtGaul.getString(), txtInd.getString());
                txtGaul.setString("");
                txtInd.setString("");
                showAlert("Success save to database");
            } else if (c == cmdUpload) {
                if (engine.dbNewWord.getLength() == 0) {
                    showAlert("No data to be uploaded");
                    return;
                }
                display.setCurrent(frmUpload);
            } else if (c == cmdListWord) {
                //read data dari
                arrNewWord = engine.dbNewWord.getPairWord();
                listNewWord.deleteAll();
                for (int i = 0; i < arrNewWord.length; i++) {
                    listNewWord.append(arrNewWord[i], null);
                }
                if (engine.dbNewWord.getLength() == 0) {
                    listNewWord.removeCommand(cmdDelete);
                } else {
                    listNewWord.addCommand(cmdDelete);
                }
                display.setCurrent(listNewWord);
            }
        } else if (d == frmUpload) {//form upload new word
            if (c == cmdBack) {
                display.setCurrent(frmAddWord);
            } else if (c == cmdUpload) {
                if (txtAuthor.getString().trim().length() == 0) {
                    showAlert("Author must be filled");
                    return;
                }
                engine.uploadNewWord(txtAuthor.getString().trim()); //proses upload
            }
        } else if (d == listNewWord) {//list new word
            if (c == cmdBack) {
                display.setCurrent(frmAddWord);
            } else if (c == cmdDelete) {
                engine.dbNewWord.clear();//proses remove
                display.setCurrent(frmAddWord);
            }
        } else if (d == listOri) {
            if (c == cmdMenu) {
                menuCanvas.reset();
                display.setCurrent(menuCanvas);
            } else if (c == cmdSelect) {
                orient = arrOrient[listOri.getSelectedIndex()];
                orientName = arrOrientName[orient];
                engine.loadData(orient);
            }
            showAlert("Orientation has changed");
        } else if (d == frmUpdate) {
            if (c == cmdMenu) {
                menuCanvas.reset();
                display.setCurrent(menuCanvas);
            } else if (c == cmdUpdate) {
                engine.update();
            }
        }
    }
}
